Defining a function that is both a generator and recursive [on hold]

Posted by user96454 on Programmers See other posts from Programmers or by user96454
Published on 2014-06-05T11:26:38Z Indexed on 2014/06/05 15:36 UTC
Read the original article Hit count: 270

Filed under:
|

I am new to python, so this code might not necessarily be clean, it's just for learning purposes. I had the idea of writing this function that would display the tree down the specified path. Then, i added the global variable number_of_py to count how many python files were in that tree. That worked as well. Finally, i decided to turn the whole thing into a generator, but the recursion breaks. My understanding of generators is that once next() is called python just executes the body of the function and "yields" a value until we hit the end of the body. Can someone explain why this doesn't work? Thanks.

import os
from sys import argv
script, path = argv

number_of_py = 0
lines_of_code = 0

def list_files(directory, key=''):
    global number_of_py
    files = os.listdir(directory)
    for f in files:
        real_path = os.path.join(directory, f)
        if os.path.isdir(real_path):
            list_files(real_path, key=key+'  ')
        else:
            if real_path.split('.')[-1] == 'py':
                number_of_py += 1
                with open(real_path) as g:
                    yield len(g.read())
            print key+real_path


for i in list_files(argv[1]):
    lines_of_code += i

print 'total number of lines of code: %d' % lines_of_code
print 'total number of py files: %d' % number_of_py

© Programmers or respective owner

Related posts about python

Related posts about python-3.x